package com.wennimei.controllers.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

import com.wennimei.domain.Answer;
import com.wennimei.domain.Music;
import com.wennimei.domain.Parameters;
import com.wennimei.domain.Picture;
import com.wennimei.domain.Soft;
import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.enums.ResponseType;
import com.wennimei.service.MessageTypeService;
import com.wennimei.service.ProcessService;

@Path("")
public class WeixinController {

    private Logger log = Logger.getLogger("WEIXIN");

    @Autowired
    private ProcessService processService;

    @Autowired
    private MessageTypeService messageTypeService;

    @Get
    @Post
    @SuppressWarnings("unchecked")
    public String index(Invocation inv) throws IOException, DocumentException {
        
        Answer a = new Answer();
        a.setId(123L);
        a.setAnswer("这是答案");
        inv.getServletContext().setAttribute("result", a);
        
        
        Map<String, Object> params = new HashMap<String, Object>();
        InputStream in = inv.getRequest().getInputStream();
        SAXReader sax = new SAXReader();
        Document document = sax.read(in);
        Element e = document.getRootElement();
        for (Iterator<Element> i = e.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            params.put(element.getName(), element.getData());
        }

        String toUserName = (String) params.get("ToUserName");
        String fromUserName = (String) params.get("FromUserName");
        String createTime = (String) params.get("CreateTime");
        String msgType = (String) params.get("MsgType");
        String msgId = (String) params.get("MsgId");
        // 文本信息
        String content = (String) params.get("Content");
        // 图片信息
        String picUrl = (String) params.get("PicUrl");
        // 地理位置信息
        String location_X = (String) params.get("Location_X");
        String location_Y = (String) params.get("Location_Y");
        String scale = (String) params.get("Scale");
        String label = (String) params.get("Label");
        // 链接信息
        String title = (String) params.get("Title");
        String description = (String) params.get("Description");
        String url = (String) params.get("Description");
        String logStr = "msgId:" + msgId + ";msgType:" + msgType
                + ";createTime:" + createTime + ";user:" + fromUserName
                + ";pic:" + picUrl + ";location_X:" + location_X
                + ";location_Y:" + location_Y + ";content:" + content
                + " ;result:%s";

        MessageTypeEnum type = this.messageTypeService.getMessageType(content,
                fromUserName);

        String result = null;
        Object res = this.processService.getContentResult(type, content,
                location_X, location_Y, fromUserName);
        if (type.getRespType().equals(ResponseType.CONTENT)) {
            if (null == res)
                res = "没有查到任何信息哦，回复h查看使用帮助！";
            result = "<xml>" + "<ToUserName><![CDATA[%s]]></ToUserName>"
                    + "<FromUserName><![CDATA[%s]]></FromUserName>"
                    + "<CreateTime>" + System.currentTimeMillis()
                    + "</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>"
                    + "<Content><![CDATA[%s]]></Content>"
                    + "<FuncFlag>0</FuncFlag>" + "</xml>";
            result = String.format(result, fromUserName, toUserName, res);
            logStr = String.format(logStr, res);
        } else if (type.getRespType().equals(ResponseType.WEIXIN_CONTENT_PIC)) {

            result = "<xml>" + "<ToUserName><![CDATA[%s]]></ToUserName>"
                    + "<FromUserName><![CDATA[%s]]></FromUserName>"
                    + "<CreateTime>" + System.currentTimeMillis()
                    + "</CreateTime>" + "<MsgType><![CDATA[news]]></MsgType>"
                    + "<ArticleCount>%s</ArticleCount>"
                    + "<Articles>%s</Articles>" + "<FuncFlag>1</FuncFlag>"
                    + "</xml>";
            String articles = "<item>" + "<Title><![CDATA[%s]]></Title>"
                    + "<Description><![CDATA[%s]]></Description>"
                    + "<PicUrl><![CDATA[%s]]></PicUrl>"
                    + "<Url><![CDATA[%s]]></Url>" + "</item>";
            StringBuilder sb = new StringBuilder();
            int size = 0;
            if (type.equals(MessageTypeEnum.PICTURE_SEARCH)) {
                List<Picture> list = (List<Picture>) res;
                for (Picture p: list) {
                    sb.append(String.format(articles, p.getTitle(),
                            p.getSummary(), p.getUrl(), p.getLink()));
                }
                size = list.size();
            } else if (type.equals(MessageTypeEnum.PARAMETER)) {
                List<Parameters> list = (List<Parameters>) res;
                for (Parameters p: list) {
                    sb.append(String.format(articles, p.getTitle(), p
                            .getParameters().replaceAll("<[^>]+>", ""), p
                            .getPicUrl(),
                            "http://wap.zol.com.cn/0/" + p.getId()
                                    + "/index.html"));
                }
                size = list.size();
            } else if (type.equals(MessageTypeEnum.SOFT_DOWN)) {
                List<Soft> softs = (List<Soft>) res;
                for (Soft s: softs) {
                    sb.append(String.format(
                            articles,
                            s.getTitle(),
                            s.getInfo(),
                            s.getPicUrl(),
                            "http://soft.3g.cn/xuan/xuanInfo.php?id="
                                    + s.getId()));
                }
                size = softs.size();
            }
            result = String.format(result, fromUserName, toUserName, size,
                    sb.toString());
            logStr = String.format(logStr, size);
        } else if (type.getRespType().equals(ResponseType.WEIXIN_MUSIC)) {

            Music music = (Music) res;

            result = "<xml>" + "<ToUserName><![CDATA[" + fromUserName
                    + "]]></ToUserName>" + "<FromUserName><![CDATA["
                    + toUserName + "]]></FromUserName>" + "<CreateTime>"
                    + System.currentTimeMillis() + "</CreateTime>"
                    + "<MsgType><![CDATA[music]]></MsgType>" + "<Music>"
                    + "<Title><![CDATA[%s]]></Title>"
                    + "<Description><![CDATA[%s]]></Description>"
                    + "<MusicUrl><![CDATA[%s]]></MusicUrl>"
                    + "<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>" + "</Music>"
                    + "<FuncFlag>0</FuncFlag>" + "</xml>";
            result = String.format(result, music.getArticle(), music.getName(),
                    music.getLowUrl(), music.getHighUrl());
            logStr = String.format(logStr, "LowUrl:" + music.getLowUrl()
                    + ";HighUrl:" + music.getHighUrl());
        }

        log.info(logStr);
        return "@" + result;
    }
}
